/*
 * @Author: taiyunhang
 * @Date: 2019-01-10 11:39:50
 * */

import { downloadBlob } from './download';
import service from '@/apis/axios.js';
import stringSplit from '@/common/utils/string-split';
import { Toast } from 'mint-ui';
import store from '@/store';
import { requestCode } from '@/env';

let fetchCount = []; // 某小段时间内正在请求的接口数量

const handleFile = (blob, filename) => {
  const reader = new FileReader();
  reader.readAsText(blob, 'utf-8');
  reader.onload = () => {
    if (reader.result) {
      try {
        const res = JSON.parse(reader.result);
        if (res && res.resultCode !== '0000') {
          Toast({ message: res.resultDesc, position: 'middle' });
        }
      } catch (e) { 
        downloadBlob(blob, filename);
      }
    }
  };
};
const guid=()=>{
  function S4() {
	  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
  return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
const axiosMethod = _config => {
  ++fetchCount;
  return service(_config)
    .then(response => {
      if (_config.file) {
        _config.filename = _config.filename
          ? _config.filename
          : stringSplit(response.headers.get('Content-Disposition'), 'filename', ';', '=');
        let file_name = stringSplit(response.headers.get('Content-Disposition'), 'filename', ';', '=');
        if (file_name) {
          return response.data.blob().then(blob => handleFile(blob, decodeURIComponent(_config.filename)));
        } else {
          return response.data;
        }
      }
      return response.data;
    })
    .then(res => {
      setTimeout(() => {
        fetchCount = fetchCount - 1 < 0 ? 0 : fetchCount - 1;
        if (fetchCount === 0) {
          store.dispatch('closeLoading');
        }
      }, 50);
      return res;
    })
    .catch(err => {
      fetchCount = fetchCount - 1;
      throw console.log(err);
    });
};

class AxiosApi {
  constructor(_url) {
    this.url = _url;
  }

  get(urlSearchParams, config = {}) {
    Object.assign(config, {
      method: 'get',
      url: this.url,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }

  post(urlSearchParams, bodyParams, config = {}) {
    let _bodyParams={
      "head": {
        "requestCode": requestCode,
        "serialno": guid()
      },
      "body":bodyParams
    };
    Object.assign(config, {
      method: 'post',
      url: this.url,
      data: _bodyParams,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }

  put(urlSearchParams, bodyParams, config = {}) {
    let _bodyParams={
      "head": {
        "requestCode": requestCode,
        "serialno": guid()
      },
      "body":bodyParams
    };
    Object.assign(config, {
      method: 'put',
      url: this.url,
      data: _bodyParams,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }

  patch(urlSearchParams, bodyParams, config = {}) {
    let _bodyParams={
      "head": {
        "requestCode": requestCode,
        "serialno": guid()
      },
      "body":bodyParams
    };
    Object.assign(config, {
      method: 'patch',
      url: this.url,
      data: _bodyParams,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }
}

const axiosResource = url => {
  return new AxiosApi(url);
};

export { axiosResource };
